package com.anb.net;

import java.util.HashMap;
import java.util.Map;

public class Error extends Exception {
    public enum Code {
        None(0),

        ConnectFailed(0x10),

        // packet parse exceptions
        PacketLengthExceeded(0x20),
        PacketReadFailed(0x21),

        RequestTimeout(0x30),

        // application level exceptions
        RuntimeException(0x80),
        NotImplemented(0x81),
        WebRequestFailed(0x82);

        private int value;

        Code(int value) {
            this.value = value;
        }

        public int getValue() {
            return value;
        }

        private static final Map<Integer, Code> valuesMap = new HashMap<Integer, Code>();
        static {
            for (Code code : Code.values()) {
                valuesMap.put(code.getValue(), code);
            }
        }

        public static Code from(int value) throws Exception {
            Code code = valuesMap.get(value);
            if (code == null) {
                throw new Exception("cannot convert Error.Code from " + value);
            }
            return code;
        }
    }

    public Error(Code error, Object obj) {
        this.error = error;
        this.obj = obj;
    }

    private Code error;
    private Object obj;

    @Override
    public String toString() {
        return String.format("%s %s", error, obj.toString());
    }
}
